package itpenguin.test;

import itpenguin.FlipperFilter;
import itpenguin.RookeryServlet;
import itpenguin.common.PMFactory;
import itpenguin.entities.Article;
import itpenguin.entities.Series;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;

public class HuddleServlet extends RookeryServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		if (req.getServletPath().equals("/upload/testdata")) {
			ServletContext context = getServletContext();
			String basePath = context.getRealPath("/WEB-INF/articles");
			List<Series> root = new ArrayList<Series>();
			for (File f : new File(basePath).listFiles()) {
				if (f.isDirectory() && !f.getName().startsWith(".")){
					Series ct = makeTree(f, null);
					root.add(ct);
				}
			}
		}
		
		// Clear cache
		FlipperFilter.clearCache();
		
		PrintWriter out = resp.getWriter();
		out.println("<html><body>");
		out.println("finished");
		out.println("</body></html>");
	}

	private Series makeTree(File baseDir, String parentId) {
		XMLInputFactory factory = XMLInputFactory.newInstance();
		Series series = null;
		File[] files = baseDir.listFiles();
		List<Article> articleList = new ArrayList<Article>();
		PersistenceManager pm = PMFactory.getInstance().getPersistenceManager();
		List<Series> seriesList = new ArrayList<Series>();

		try {
			for (File f : files) {
				if (f.getName().equals("series.xml")) {
					series = makeSeries(factory.createXMLEventReader(new FileReader(f)));
				}
			}
				
			for (File f : files) {
				if (f.getName().startsWith(".") || f.getName().equals("series.xml")) {
				} else if (f.isDirectory()) {
					Series newSeries = makeTree(f.getAbsoluteFile(), series.getId());
					seriesList.add(newSeries);
				} else if (f.getName().equals("series.xml")) {
				} else {
					Article a = makeArticle(factory.createXMLEventReader(new FileReader(f)));
					a.setLastModified(new Date());
					articleList.add(a);
				}
			}
		} catch (FileNotFoundException e1) {
		} catch (XMLStreamException e1) {
		}

		Collections.sort(articleList, new Comparator<Article>(){
			@Override
			public int compare(Article o1, Article o2) {
				return o1.getPublished().compareTo(o2.getPublished());
			}
		});
		
		int partNo = 0;
		Date lastDate = new Date(Integer.MIN_VALUE);
		if (seriesList.size() == 0) {
			for(Article a : articleList)
			{
				a.setPartNumber(++partNo);
				a.setParentId(series.getId());
				if (lastDate.compareTo(a.getPublished()) < 0) {
					lastDate = a.getPublished();
				}
				pm.makePersistent(a);
			}
		} else {
			for(Series s : seriesList){
				if (lastDate.compareTo(s.getPublished()) < 0) {
					lastDate = s.getPublished();
				}
			}
		}
		series.setPublished(lastDate);
		series.setParentId(parentId);
		pm.makePersistent(series);
		
		pm.close();
		
		return series;
	}
}
